package com.dge.common.other

import com.hjq.toast.ToastParams
import com.hjq.toast.ToastUtils
import com.hjq.toast.config.IToastInterceptor
import com.dge.common.action.ToastAction
import com.dge.common.base.view.BaseActivity
import com.dge.common.base.view.BaseFragment
import com.dge.common.common.AppConfig
import timber.log.Timber

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject-Kotlin
 *    time   : 2020/11/04
 *    desc   : 自定义 Toast 拦截器（用于追踪 Toast 调用的位置）
 */
class ToastLogInterceptor : IToastInterceptor {
    override fun intercept(params: ToastParams?): Boolean {
        if (AppConfig.isDebug()) {
            // 获取调用的堆栈信息
            val stackTrace: Array<StackTraceElement> = Throwable().stackTrace
            // stackTrace.forEach {
            //     Timber.i(it.className + "; " + it.lineNumber)
            // }
            // 跳过最前面两个堆栈
            var i = 2
            while (stackTrace.size > 2 && i < stackTrace.size) {
                // 获取代码行数
                val lineNumber: Int = stackTrace[i].lineNumber
                // 获取类的全路径
                val className: String = stackTrace[i].className
                if (((lineNumber <= 0) || className.startsWith(BaseFragment::class.java.name)
                            || className.startsWith(BaseActivity::class.java.name)
                            || className.startsWith(ToastUtils::class.java.name)
                            || className.startsWith(ToastAction::class.java.name))
                ) {
                    i++
                    continue
                }
                Timber.tag("ToastUtils")
                    .i("(%s:%s) %s", stackTrace[i].fileName, lineNumber, params?.text?.toString() ?: "")
                break
            }
        }
        return false
    }
}